package com.ruoyi.web.controller.jiuyezu;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;

import java.util.ArrayList;
import java.util.List;

public class AiCommunicationUtil {
    static {
//         以下赋值语句请放在类或方法中运行
//        访问下面的链接获取Key，用支付宝登录即可
//        https://dashscope.console.aliyun.com/apiKey?spm=a2c4g.11186623.0.0.414546c1MKSX02
        Constants.apiKey = "";
    }

    /**
     * 发送消息给AI并接收响应。
     *
     * @param systemPrompt 系统提示信息。
     * @param userPrompt 用户输入的提示信息。
     * @return AI的响应内容。
     * @throws ApiException 如果API调用失败。
     * @throws NoApiKeyException 如果未设置API Key。
     * @throws InputRequiredException 如果输入参数不满足要求。
     */
    public static String sendToAiAndReceiveResponse(String userPrompt) throws ApiException, NoApiKeyException, InputRequiredException {
        List<Message> messages = new ArrayList<>();
        messages.add(createMessage(Role.SYSTEM, "You are a helpful assistant."));
        messages.add(createMessage(Role.USER, userPrompt));

        GenerationParam param = createGenerationParam(messages);
        GenerationResult result = callGenerationWithMessages(param);

        return result.getOutput().getChoices().get(0).getMessage().getContent();
    }

    private static GenerationParam createGenerationParam(List<Message> messages) {
        return GenerationParam.builder()
                .model("qwen-turbo")
                .messages(messages)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .build();
    }

    private static GenerationResult callGenerationWithMessages(GenerationParam param) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        return gen.call(param);
    }

    private static Message createMessage(Role role, String content) {
        return Message.builder().role(role.getValue()).content(content).build();
    }
}